import { Op } from "sequelize";
import Role from "../model/role.model";

class RoleService {
    //根据条件查询菜单
    async findInfo({ name, code,id }) {
        let whereOpt = {}
        if (name) {
            let options = { name }
            let res = await Role.findOne({
                where: options
            });
            if (res?.dataValues) {
                return res?.dataValues
            }
        }
        if (code) {
            let options = { code }
            let res = await Role.findOne({
                where: options
            });
            if (res?.dataValues) {
                return res?.dataValues
            }
        }
        if (id) {
            let options = { id }
            let res = await Role.findOne({
                where: options
            });
            if (res?.dataValues) {
                return res?.dataValues
            }
        }
    }
    //新增
    async create({ name, code, status,permission, comment }) {
        const res = await Role.create({ name, code,permission, status, comment });
        return res.dataValues;
    }
    //删除
    async delete({ ids }) {
        const res = await Role.destroy({ where: { id:ids } })
        return res > 0 ? true : false;
    }
    //更新
    async update({ id, name, code,permission, status, comment }) {
        let whereOpt = { id };
        let params = {};
        name && Object.assign(params, { name })
        code && Object.assign(params, { code })
        status && Object.assign(params, { status })
        comment && Object.assign(params, { comment })
        permission && Object.assign(params, { permission })
        const res = await Role.update(params, { where: whereOpt });
        return res[0] > 0 ? true : false
    }
    //列表
    async getList({ id = '', name = '', code, status }) {
        let whereOpt = {};
        name && Object.assign(whereOpt, { name: { [Op.like]: `%${name}%` } })
        id && Object.assign(whereOpt, { id })
        code && Object.assign(whereOpt, { code })
        status && Object.assign(whereOpt, { status })
        let res = await Role.findAll({
            where: whereOpt,
            raw: true
        })
        return res || null
    }
}

export default new RoleService